package com.video.gateway.filters;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.text.AntPathMatcher;
import com.video.common.exception.BaseException;
import com.video.common.result.ResponseResult;
import com.video.gateway.config.AuthProperties;
import com.video.gateway.utils.JwtTool;
import lombok.RequiredArgsConstructor;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;


@Component
@RequiredArgsConstructor
public class AuthGlobalFilter implements GlobalFilter, Ordered {

    private final JwtTool jwtTool;

    private final AuthProperties authProperties;

    private final AntPathMatcher antPathMatcher = new AntPathMatcher();


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 1 获取request对象
        ServerHttpRequest request = exchange.getRequest();


        // 2. 根据路径判断是否放行
        if (isExClude(request.getPath().toString())) {
            return chain.filter(exchange);
        }

        // 3. 获取请求头
        List<String> authorization = request.getHeaders().get("authorization");

        String token = "";
        // 4. 判断是否存在请求头
        if (CollUtil.isNotEmpty(authorization)) {
            token = authorization.get(0);
        }

        // 5.解析token(jwtUtil已经做了判断校验)
        Long userId = null;
        try {
            userId = jwtTool.parseToken(token);
        } catch (BaseException e) {
            System.out.println("网关token解析失败");
            // 拦截
            ServerHttpResponse response = exchange.getResponse();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        // 6. 传递用户信息
        String userInfo = userId.toString();
        ServerWebExchange buildExchange = exchange.mutate().request(builder -> builder.header("user-info", userInfo)).build();
        return chain.filter(buildExchange);
    }

    private boolean isExClude(String path) {
        // 拿到yml配置里面的配置列表
        List<String> excludePaths = authProperties.getExcludePaths();
        for (String pattern : excludePaths) {
            // 校验
            if (antPathMatcher.match(pattern, path)) {
                return true;
            }
        }
        return false;
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
